package novanok.com.tracktweet;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import twitter4j.HashtagEntity;

public class MapReduceHashTags {

    private Map<String, Integer> hashtags = new TreeMap<String, Integer>();
    private double FACTOR_HASHTAG = 0.2;

    private int limiteHashtag = 0;

    public MapReduceHashTags(){ }

    public void analizar( HashtagEntity[] hashtags ){
        synchronized (this.hashtags) {
            for (int i = 0; i < hashtags.length; i++) {
                String valor = hashtags[i].getText().toUpperCase();

                if (this.hashtags.get(valor) != null)
                    this.hashtags.put(valor, this.hashtags.get(valor) + 1);
                else
                    this.hashtags.put(valor, 1);
            }
        }

        this.purgar();
        this.actualizarLimite();
    }

    private void purgar(){
        synchronized (hashtags) {
            if ( hashtags.size() > 10 ) {
                List<String> remove = new LinkedList<String>();

                for (Map.Entry<String, Integer> v : hashtags.entrySet())
                    if (v.getValue() == limiteHashtag)
                        remove.add(v.getKey());

                for (String s : remove)
                    hashtags.remove(s);
            }
        }
    }

    private void actualizarLimite(){
        Map<String, Integer> lista = getHashtagsOrdenados();

        if ( lista != null && lista.values().size() > 0 )
            this.limiteHashtag = ( int )( ( double ) lista.values().iterator().next() * FACTOR_HASHTAG );
    }

    public synchronized Map<String, Integer> getHashtagsOrdenados(){
        synchronized (hashtags) {
            return Comun.sortByValues(hashtags);
        }
    }

    public void clear() {
        hashtags.clear();
    }
}
